package com.bigpang.framework.docedit.word.util;

import com.bigpang.framework.docedit.word.config.FileGenerateConfig;
import com.bigpang.framework.docedit.word.config.TableConfig;
import com.bigpang.framework.docedit.word.entity.TableRowEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author YongQiang
 * @Date 2021/4/6 15:04
 * @Version 1.0
 */
public class GenUtils {

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("templates/dto.java.vm");
        return templates;
    }

    public static void generatorCode(List<Table> tableList, FileGenerateConfig generateParam, ZipOutputStream zip) throws Exception {
        int index=0;
        //循环遍历读取到的表格
        for (Table table : tableList) {
            index++;
            TableConfig tableConfig = generateParam.getTableConfig();
            //获取字段类型映射配置
            Configuration typeConfigure = getTypeConfig(tableConfig.getTypeConfigFilePath());
            List<TableRowEntity> tables = new ArrayList<>();
            String importList;
            for (int i = tableConfig.getStartRows(); i < table.numRows(); i++) {
                TableRow row = table.getRow(i);
                TableRowEntity columnDto = new TableRowEntity();
                columnDto.setAttributeName(row.getCell(tableConfig.getAttributeOffset()).text().trim());
                columnDto.setAttributeComment(row.getCell(tableConfig.getCommentOffset()).text().replace("\n"," ").replace(
                        "\r"," ").replace("\t"," ").trim());
                columnDto.setTypeName(tableConfig.getTypeOffset() == null ? "String":
                        row.getCell(tableConfig.getTypeOffset()).text().trim());
                columnDto.setTypeName(typeConfigure.getString(columnDto.getTypeName(), "String"));
                tables.add(columnDto);
            }
            //设置velocity资源加载器
            Properties prop = new Properties();
            prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            Velocity.init(prop);

            Map<String, Object> map = new HashMap<>(16);
            map.put("className", tableConfig.getClassName()+index);
            map.put("comments", tableConfig.getClassComment());
            map.put("table", tables);
            VelocityContext context = new VelocityContext(map);
            //获取模板列表
            List<String> templates = getTemplates();
            for (String template : templates) {
                //渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, "UTF-8");
                tpl.merge(context, sw);

                try {
                    //添加到zip
                    zip.putNextEntry(new ZipEntry(getFileName(template, tableConfig.getClassName()+index)));
                    IOUtils.write(sw.toString(), zip, "UTF-8");
                    IOUtils.closeQuietly(sw);
                    zip.closeEntry();
                } catch (IOException e) {
                    throw new Exception("渲染类文件失败，类名：" + tableConfig.getClassName(), e);
                }
            }
        }
    }

    /**
     * 获取配置信息
     */
    public static Configuration getTypeConfig(String configureName) throws Exception {
        try {
            return new PropertiesConfiguration(configureName);
        } catch (ConfigurationException e) {
            throw new Exception("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className) {

        if (template.contains("dto.java.vm")) {
            return className + "Dto.java";
        }

        return null;
    }
}
